package com.example.blades.myintentreceiver;

import android.content.Intent;
import android.content.IntentFilter;
import android.net.nsd.NsdManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class IntentReceiver extends AppCompatActivity {
    private Button btn_register=null;
    private Button btn_unregister=null;
    private SMSReceiver smsReceiver=null;

    private static final String SMS_ACTION="android.provider.Telephony.SMS_RECEIVED";

    private Button btn=null;
    private final String nobody="Nobody.doesnt.need.a.name";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_receiver);

        btn=(Button) findViewById(R.id.btn);
        btn.setOnClickListener(new MyButtonListener());

        btn_register=(Button)findViewById(R.id.btn_register);
        btn_unregister=(Button)findViewById(R.id.btn_unregister);
        btn_register.setOnClickListener(new RegisterReceiverListener());
        btn_unregister.setOnClickListener(new UnRegisterReceiverListener());

    }

    class MyButtonListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {
            //生成一个新的Intent对象
            Intent intent=new Intent(nobody);
            //在Intent对象中添加一个键值对
            intent.putExtra("testIntent","Hello Intent.");
            sendBroadcast(intent);
        }
    }

    class RegisterReceiverListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {
            //生成一个BroadcastReceiver对象
            smsReceiver=new SMSReceiver();
            //生成一个IntentFilter对象
            IntentFilter filter=new IntentFilter();
            //为IntentFilter添加一个Action
            filter.addAction(SMS_ACTION);
            //将BroadcastReceiver对象注册到系统中
            IntentReceiver.this.registerReceiver(smsReceiver,filter);
        }
    }

    class  UnRegisterReceiverListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {
            //解除BroadcastReceiver对象的注册
            IntentReceiver.this.unregisterReceiver(smsReceiver);
        }
    }
}
